<?
header('Content-Type:text/html;charset=utf-8'); 
session_start();
if( !isset($_SESSION['last_key']) ) header("Location: index.php");
include_once( 'config.php' );
include_once('weibooauth.php');
include_once ('saemysql.class.php');
$statusurl = $_POST['statusurl'];
$statusurl = trim($statusurl);
//echo $statusurl;
$mid = strrchr($statusurl, "/");
if($mid){
    //FIXME: hard code length
	$mid = substr( $mid, 1,9);
}
$firstpart= substr($mid,0,1);
//echo $firstpart." ";
$secondpart=substr($mid,1,4);
//echo $secondpart." ";
$thirdpart=substr($mid,5,8);
//echo $thirdpart;
$statusid =  dec10($firstpart).dec10($secondpart).dec10($thirdpart);
if($statusid < 1){
    echo "请检查输入<br/>";
}
if(isset($_GET['statusid'])) $statusid = $_GET['statusid'];
$max = 2000;
$pagesizemax = 200;
$sae = new SaeTClient(WB_AKEY, WB_SKEY, $_SESSION['last_key']['oauth_token'], $_SESSION['last_key']['oauth_token_secret']);
$status = $sae->show_status($statusid);

$repeat = 2;
$status = $sae->show_status($statusid);
for ($i = 0; ($i < $repeat) && ($status['user']['screen_name'] == null); $i++){
	$status = $sae->show_status($statusid);
}

//var_dump($_SESSION['last_key']);
//var_dump($status);
// if the id exists
$creater = $status['user']['screen_name'];
$coverArea = $status['user']['followers_count'];
if($creater == null) {
    echo "不好意思，似乎出错了~<br/>";
    echo "<a href='influence.php'>返回再试一次</a>";
    exit();
}

$statusDigest = cut_str($status['text'], 15);

$user_followers = array();

$countArray = $sae->get_count_info_by_ids(array($statusid));
$count = 0;

for ($i = 0; ($i < $repeat) && (count($countArray) < 1); $i++){
	$countArray = $sae->get_count_info_by_ids(array($statusid));
}

if(count($countArray) >= 1){
    $count = $countArray[0]['rt'];
}

$comments_total = $count;


//calculate page_high
if (floor($count/$pagesizemax) != ($count/$pagesizemax)){
	$page = floor($count/$pagesizemax)+1;
}else{
	$page = $count/$pagesizemax;
}


$records = array();

//create $records array
if ($count == 0){
	//if (count($sae->repost_timeline($statusid, (($max/$pagesizemax)+1), $pagesizemax))>0){
	//	echo "不好意思，不会分析这个微博地址";	    
	//    exit();
	//}
	$repeat = 3;
	for ($i = 1; $i <= ($max/$pagesizemax); $i++){
		$ret = $sae->repost_timeline($statusid, $i, $pagesizemax);
		if (count($ret) == 0){
			if ($repeat > 0){
				$i--;
				$repeat--;
			}
		}else{
			$records = array_merge($records, $ret);
			$repeat = 3;
		}
	}
	if (count($records) == 0){
		echo "不好意思，不会分析这个微博地址";	    
	    exit();
	}
	
	//reverse order of array
	for ($i = 0; $i < (count($records)-1-$i); $i++){
		$help = $records[$i];
		$records[count($records)-1-$i] = $i;
		$records[$i] = $help;
	}
}else{
	if (floor($count/$pagesizemax) != ($count/$pagesizemax)){
		$page = floor($count/$pagesizemax)+1;
	}else{
		$page = $count/$pagesizemax;
	}
	while ($page > 0 and count($records) <= $max){
		$ret = $sae->repost_timeline($statusid, $page, $pagesizemax);
		$records = array_merge($ret, $records);	
		$page--;
	}
}





//run through array, start at the back (oldest first)

$root_children = array();
$maxlevel = 0;

$counter = 1;
$posterArray = array();
$posterArray[$creater] = array('id'=>1, 'name'=>$creater, 'children'=> array());

for ($i = count($records)-1; $i >= 0; $i--){
	
	if (!isset($posterArray[$records[$i]['user']['screen_name']])){
		
		$before = parseAt($records[$i]['text']);
		//check before
		if (count($before)>0){
			$before = array_unique($before);
			for ($a = 0; $a < count($before); $a++){
				if (trim($before[$a]) == trim($records[$i]['user']['screen_name'])){
					for ($aa = $a; $aa < count($before)-1; $aa++){
						$before[$aa] = $before[$aa+1];
					}
					$before[count($before)-1] = '';
				}
			}
			
		}
		
		array_push($before, $creater);
		
		$coverArea += $records[$i]['user']['followers_count'];
		$user_followers[$records[$i]['user']['screen_name']] = $records[$i]['user']['followers_count'];
		
		if (!isset($posterArray[trim($before[0])])){
			$counter++;
			$posterArray[$records[$i]['user']['screen_name']] = array('id'=>$counter, 'name'=>$records[$i]['user']['screen_name'], 'children'=>array());
			$counter++;
			$child = array('id'=>$counter, 'name'=>$before[0], 'children'=>array());
			array_push($child['children'], &$posterArray[$records[$i]['user']['screen_name']]);
			
			for ($a = 1; $a < count($before); $a++){
				if (isset($posterArray[trim($before[$a])])){
					$posterArray[$before[$a-1]] = $child;
					array_push($posterArray[trim($before[$a])]['children'], &$posterArray[$before[$a-1]]);
					$a = count($before);
				}else{
					$counter++;
					$posterArray[$before[$a-1]] = $child;
					$child = array('id'=>$counter, 'name'=>$before[$a], 'children'=>array());
					array_push($child['children'], &$posterArray[$before[$a-1]]);
				}
				
				
			}
			
			
		}else{
			$counter++;
			$posterArray[$records[$i]['user']['screen_name']] = array('id'=>$counter, 'name'=>$records[$i]['user']['screen_name'], 'children'=> array());
			array_push($posterArray[trim($before[0])]['children'], &$posterArray[$records[$i]['user']['screen_name']]);
		}
	}
}
// find the exploding point
$explode = array();
$shareString = "@".$creater." 的微博：".$statusDigest." 的#关键传播节点#：";
$posterArray[$creater]['followers']=$status['user']['followers_count'];
foreach($posterArray[$creater]['children'] as &$child){
    $childCnt = getChildrenCnt($child)+1;
    $values = getChildrenCntBetter($child, array('count'=>0, 'followers'=>0), $user_followers);

    if ($user_followers[$child['name']] != null){
    	$values['followers'] -= $user_followers[$child['name']];
    	$tmp = array('name'=>$child['name'], 'count'=>$values['count'], 'followers'=>$user_followers[$child['name']], 'behind_followers'=>$values['followers']);
    }else{
    	$tmp = array('name'=>$child['name'], 'count'=>$values['count'], 'followers'=>'-', 'behind_followers'=>$values['followers']);
    } 
    
    array_push($explode, $tmp);
}

usort($explode, "cmpExplode");

if(isset($explode[0]))
    $shareString .= "@".$explode[0]['name']." (".$explode[0]['count']."次) ";
if(isset($explode[1]))
    $shareString .= "@".$explode[1]['name']." (".$explode[1]['count']."次) ";
if(isset($explode[2]))
    $shareString .= "@".$explode[2]['name']." (".$explode[2]['count']."次) ";
$shareString .= "看详细传播图请点http://newgraph.sinaapp.com/getinfluence.php?statusid=".$statusid."";

$jsonString =  json_encode($posterArray[$creater]);
//store the result in database
$stringLength = strlen($jsonString);
$jsonString1="";
$jsonString2="";
if($stringLength%2 !=0){
    $jsonString1 = substr($jsonString, 0, floor($stringLength/2));
    $jsonString2 = substr($jsonString, floor($stringLength/2));
} else {
    $jsonString1 = substr($jsonString, 0, $stringLength/2);
    $jsonString2 = substr($jsonString, $stringLength/2);
}
$mysql = new SaeMysql();
$sql = "select * from json where statusid = '".$statusid."'";
$data = $mysql->getData( $sql );
if($data == false){
	$mysql->runSql("set names 'utf8'");
	$sql1 = "INSERT  INTO json (statusid, jsonstring1, sharestring) VALUES ( '".$statusid."' , '".$mysql->escape($jsonString1)."', '".$mysql->escape($shareString)."')";
        $mysql->runSql($sql1);
        $sql2 = "update json set jsonstring2 = '".$mysql->escape($jsonString2)."' where statusid='".$statusid."'";
	$mysql->runSql($sql2);
} else {
        $mysql->runSql("set names 'utf8'");
	$sql3 = "update json set jsonstring1 = '".$mysql->escape($jsonString1)."', sharestring = '".$mysql->escape($shareString)."' where statusid='".$statusid."'";
	$mysql->runSql($sql3);
        $sql4 = "update json set jsonstring2 = '".$mysql->escape($jsonString2)."' where statusid='".$statusid."'";
	$mysql->runSql($sql4);
}
$mysql->closeDb();

/**
 * Given a string, parse all the repost users
 * @param type $string 
 * @return array of screen_name
 */
function parseAt($string){
    $pattern = "/\/\/\s?@(\S*?)[\:|\：|\: ]/u";
    preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);
    return $matches[1];
}
/**
 * recursive call not working I guess there is a circle...
 * now cheated with five loops
 * @param type $array
 * @return count 
 */

function getChildrenCnt($array){
    $count = count($array['children']);
    foreach($array['children'] as $child1){
        $count += count($child1['children']);
        foreach($child1['children'] as $child2){
            $count += count($child2['children']);
            foreach($child2['children'] as $child3){
                $count += count($child3['children']);
                foreach($child3['children'] as $child4){
                    $count += count($child4['children']);
                }
            }
        }
    }
    return $count;
}

function getChildrenCntBetter(&$array, $values, $user_followers){
	$values['count'] += count($array['children']);
	$values['followers'] += $user_followers[$array['name']];
	$array['followers']=$user_followers[$array['name']];
	for ($i = 0; $i < count($array['children']); $i++){
		$values = getChildrenCntBetter($array['children'][$i], $values, $user_followers);
	}
	
	return $values;
}

function cmpExplode($a, $b){
    if ($a['count'] == $b['count']) {
        return 0;
    }
    return ($a['count'] > $b['count']) ? -1 : 1;
}




//**********************新增，字符截断处理函数××××××××××××××××××××××××××××××××××

function cut_str($sourcestr,$cutlength) 
{ 
   $returnstr=''; 
   $i=0; 
   $n=0; 
   $str_length=strlen($sourcestr);//字符串的字节数 
   while (($n<$cutlength) and ($i<=$str_length)) 
     { 
      $temp_str=substr($sourcestr,$i,1); 
      $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码 
      if ($ascnum>=224)    //如果ASCII位高与224，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符         
         $i=$i+3;            //实际Byte计为3
         $n++;            //字串长度计1
      }
        elseif ($ascnum>=192) //如果ASCII位高与192，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符 
         $i=$i+2;            //实际Byte计为2
         $n++;            //字串长度计1
      }
        elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,1); 
         $i=$i+1;            //实际的Byte数仍计1个
         $n++;            //但考虑整体美观，大写字母计成一个高位字符
      }
        else                //其他情况下，包括小写字母和半角标点符号，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,1); 
         $i=$i+1;            //实际的Byte数计1个
         $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
      } 
     } 
           if ($str_length>$cutlength){
          $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
      }
      return $returnstr; 

}

//存储下载session数组
$_SESSION['download']=$explode;


?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>寻找微博引爆点 草根版</title>

<!-- CSS Files -->
<link type="text/css" href="css/base.css" rel="stylesheet" />
<link type="text/css" href="css/Hypertree.css" rel="stylesheet" />
<link type="text/css" href="css/table.css" rel="stylesheet" />


<!--[if IE]><script language="javascript" type="text/javascript" src="js/excanvas.js"></script><![endif]-->

<!-- Jquery Library File -->
<script language="javascript" type="text/javascript" src="js/jquery.js"></script>

<!-- DataTables Library File -->
<script language="javascript" type="text/javascript" src="js/jquery.dataTables.js"></script>

<!-- JIT Library File -->
<script language="javascript" type="text/javascript" src="js/jit.js"></script>

<script type="text/javascript" charset="utf-8">
	$(document).ready(function() {
		$('#details').dataTable( {
			"aaSorting": [[ 2, "desc" ]]
		} );
	} );
</script>

<!-- HyperTree -->
<script language="javascript" type="text/javascript">
var labelType, useGradients, nativeTextSupport, animate;

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport 
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'Native';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();



function init(){
    //init data
    var json = <?php echo $jsonString?>;
    var infovis = document.getElementById('infovis');
    //var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
    var w = 1000, h = 1000;
    //init Hypertree
    var ht = new $jit.Hypertree({
      //id of the visualization container
      injectInto: 'infovis',
      //canvas width and height
      width: w,
      height: h,
      //Change node and edge styles such as
      //color, width and dimensions.
      Node: {
          dim: 3,
          color: "#f00"
      },
      Edge: {
          lineWidth: 1,
          color: "#088"
      },
      onBeforeCompute: function(node){
          //Log.write("centering");
      },
      //Attach event handlers and add text to the
      //labels. This method is only triggered on label
      //creation
      onCreateLabel: function(domElement, node){
          domElement.innerHTML = node.name;
          $jit.util.addEvent(domElement, 'click', function () {
              ht.onClick(node.id, {
                  onComplete: function() {
                      ht.controller.onComplete();
                  }
              });
          });
      },
      //Change node styles when labels are placed
      //or moved.
      onPlaceLabel: function(domElement, node){
          var style = domElement.style;
          style.display = '';
          style.cursor = 'pointer';
          if (node._depth < 1) {
              style.fontSize = "0.7em";
              style.color = "#555";

          } else if(node._depth == 1){
              style.fontSize = "0.6em";
              style.color = "#555";
          } else if(node._depth == 2){
              style.fontSize = "0.5em";
              style.color = "#555";

          } else {
              style.fontSize = "0.2em";
              style.color = "#555";
          }

          var left = parseInt(style.left);
          var w = domElement.offsetWidth;
          style.left = (left - w / 2) + 'px';
      },
      
      onComplete: function(){
          //Log.write("done");
          
          //Build the right column relations list.
          //This is done by collecting the information (stored in the data property) 
          //for all the nodes adjacent to the centered node.
          var node = ht.graph.getClosestNodeToOrigin("current");
      }
    });
    //load JSON data.
    ht.loadJSON(json);
    //compute positions and plot.
    ht.refresh();
    //end
    ht.controller.onComplete();
    var c = document.getElementById('infovis-canvas');
    
    $("#repostBtn1").click(function(){
        if ( $.browser.msie ) {
            $.post('repost.php',{text:$("#comment1").val(), image: "http://newgraph.sinaapp.com/image/explode.png"});
        } else {
            $.post('repost.php',{text:$("#comment1").val(), image: c.toDataURL("image/png")});
        }
        //alert("xx:"+c.toDataURL("image/png"));
        $("#onrepost1").show();
        $("#repostForm1").hide();
        $("#repostForm2").hide();
        return false;
    });
    
    $("#repostBtn2").click(function(){
        if ( $.browser.msie ) {
            $.post('repost.php',{text:$("#comment2").val(), image: "http://newgraph.sinaapp.com/image/explode.png"});
        } else {
            $.post('repost.php',{text:$("#comment2").val(), image: c.toDataURL("image/png")});
        }
        $("#onrepost2").show();
        $("#repostForm1").hide();
        $("#repostForm2").hide();
        return false;
    });
}

function checkNum (){
	var text1 = document.getElementById("comment1").value;
        var text2 = document.getElementById("comment2").value;
	var len;
	var olen = 180;
	if(text1.length >= olen){
		$("#countTxt1").html('<span style="color:red">0</span>');
		document.getElementById("comment1").value = text1.substr(0,olen);		
	}else{ 
		$("#countTxt1").html('<span style="color:green">'+(olen - text1.length)+'</span>');
	}	
        if(text2.length >= olen){
		$("#countTxt2").html('<span style="color:red">0</span>');
		document.getElementById("comment2").value = text2.substr(0,olen);		
	}else{ 
		$("#countTxt2").html('<span style="color:green">'+(olen - text2.length)+'</span>');
	}
}



</script>
<style type="text/css">
<!--
.STYLE1 {color: #FF0000}
.STYLE2 {font-size: small}
-->
</style>
</head>

<body onload="init();">

<br></br>

<center>
<table>
<tr>
<td valign="top">
<div style="border: 1px solid #E9E9E9; background-color: white;width:300px;height:104px">
<br>
<table width="260px" style="text-align: left; valign: top; padding-left:20px; padding-top:7px;">
<tr><td><b>转发总量:</b></td><td><?php echo $comments_total;?></td></tr>
<tr><td><b>分析的转发:</b></td><td><?php echo count($records);?></td></tr>
<tr><td><b>转发覆盖人数:</b></td><td><?php echo $coverArea;?></td></tr>
</table>
</div>
</td>
<td widht"30px">&nbsp</td>
<td>

<p id="onrepost1" style="display:none;">分享成功</p>
<form id="repostForm1" action="">
      <textarea class="textarea" name="content" id="comment1" style="width:500px;height:100px;margin:0px;" onKeyUp="checkNum()" onBlur="checkNum()" onFocus="checkNum()"><?php echo $shareString?></textarea>
      <p align="center"><label style="color:#999;">还能输入 <span id="countTxt1" style="font-size:18px;color:green"><span style="color:green">140</span></span> 个字</label>
          <input name="submit" type="submit" class="btn" id="repostBtn1" style="height:40px;width:140px;" value="转发到微博"></p>
</form>

</td>
</tr>
</table>
</center>

<h2>点击<span class="STYLE1">红点</span>可以切换该用户为中心节点哦~</h2>

<div id="container">
    <div id="infovis"></div>    
</div>


<center>
<table>
<tr>
<td>

<table cellpadding="0" cellspacing="0" border="0" class="display" id="details">
	<thead>
          <tr>
                <th>#</th>
                <th>转发者</th>
                <th>带来转发量</th>
                <th>粉丝总量</th>
                <th>转发者的粉丝</th>
                <th>带来转发用户的粉丝</th>
          </tr>
    </thead>
    <tbody>
          <?php
            $i=1;
            foreach($explode as $e){
              ?>
          <tr>
                <td><?php echo $i;?></td>
                <td><?php echo $e['name'];?></td>
                <td><?php echo $e['count'];?></td>
                <td><?php echo ($e['followers']+$e['behind_followers']);?></td>
                <td><?php echo $e['followers'];?></td>
                <td><?php echo $e['behind_followers'];?></td>
          </tr>
          <?php
               $i++; }
          ?>
    </tbody>
    </table>

</td>
<td>



</td>
</tr>

</table>
</center>
<br>
<p>
    <a href='download.php' >点击下载</a>
</p>
<br><br>
<a href='influence.php'>返回首页</a>
<script src="http://s96.cnzz.com/stat.php?id=3764558&web_id=3764558&show=pic" language="JavaScript"></script>
</body>

</html>
